package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
)

func main() {
	router := gin.Default()
	router.GET("/header", func(c *gin.Context) {
		// 不区分大小写，单词之间用"-"连接
		// 用于获取一个请求头，重复的请求头只能获取第一个
		c.JSON(http.StatusOK, gin.H{
			"user-agent": c.GetHeader("user-agent"),
			"User-agent": c.GetHeader("User-agent"),
			"user-Agent": c.GetHeader("user-Agent"),
			"user-AGent": c.GetHeader("user-AGent"),
			"userAgent":  c.GetHeader("userAgent"),
		})
	})
	router.GET("/headers", func(c *gin.Context) {
		c.JSON(http.StatusOK, c.Request.Header)
	})

	// 用户和爬虫区别对待
	router.GET("/index", func(c *gin.Context) {
		userAgent := c.GetHeader("User-Agent")
		// 1.使用正则匹配
		// 2.使用字符串包含匹配
		if strings.Contains(userAgent, "python") {
			fmt.Println("字符串匹配出爬虫")
			c.JSON(http.StatusOK, gin.H{"data": "爬虫数据"})
			return
		}
		c.JSON(http.StatusOK, gin.H{"data": "用户数据"})
	})

	router.GET("/header/set", func(c *gin.Context) {
		c.Header("token", "akjsghasjkdfgghaskdfgasjkhdfg")
		c.String(http.StatusOK, "看看header")
	})
	router.Run(":8080")
}
